package cn.sunshine.comprehensive.factory_singleton;

import cn.sunshine.comprehensive.factory_singleton.factory.AClusterFactory;
import cn.sunshine.comprehensive.factory_singleton.factory.BClusterFactory;
import cn.sunshine.comprehensive.factory_singleton.factory.ClusterAbstractFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @Description
 *  1. 通过读取配置文件动态创建抽象工厂类
 *  2. 将抽象工厂单例化, 同时可以使用 prototype 动态配置抽象工厂
 * @Author Mokairui
 * @Since 2022/1/2
 */
public class ClusterStore {

    // 通过反射动态获取的方式
    private static final String CLUSTER_CLASS_PREFIX = "cn.sunshine.comprehensive.factory_singleton.factory.";

    static {
        InputStream is = ClusterStore.class.getClassLoader().getResourceAsStream("cluster.properties");
        Properties properties = new Properties();
        try {
            properties.load(is);
            String fullQualifiedClassName = CLUSTER_CLASS_PREFIX + properties.getProperty("cluster");
            ClusterHolder.clusterFactory = ((ClusterAbstractFactory) Class.forName(fullQualifiedClassName)
                    .getDeclaredConstructor().newInstance());
        } catch (Exception e) {
            throw new RuntimeException("An error occurred while create abstract factory");
        }
    }

    public static ClusterAbstractFactory getClusterFactory() {
        return ClusterHolder.clusterFactory;
    }


    // 封装为单例的方式
    public static ClusterAbstractFactory getAClusterFactory() {
        return ClusterHolder.clusterAFactory;
    }

    public static ClusterAbstractFactory getBClusterFactory() {
        return ClusterHolder.clusterBFactory;
    }

    private static final class ClusterHolder {

        private static final ClusterAbstractFactory clusterAFactory = new AClusterFactory();

        private static final ClusterAbstractFactory clusterBFactory = new BClusterFactory();

        private static ClusterAbstractFactory clusterFactory;

    }

}
